﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.Hosting;
using System.Net.Mail;
using System.Text.RegularExpressions;
using VioletDevelopmentLaboratory.Net.Web.Configuration;

namespace VioletDevelopmentLaboratory.Net.Web
{
	public sealed class VUtility
	{
		private VUtility() { }

		public static String RemoveHtmlTag(String source)
		{
			if (source == null)
				throw new ArgumentNullException("source");

			if (String.IsNullOrEmpty(source))
				throw new ArgumentOutOfRangeException("source");

			String[] patterns = { "<script[^>]*?>.*?</script>", "<style[^>]*?>.*?</style>", @"<[\/\!]*?[^<>]*?>", @"([\r\n])[\s]" };

			for (int i = 0; i < patterns.Length; i++)
			{
				source = Regex.Replace(source, patterns[i], "", RegexOptions.IgnoreCase);
			}

			return source;
		}

		public static String GetFormatFileLength(Double fileLength)
		{
			if (fileLength < 0)
				throw new ArgumentOutOfRangeException("fileLength");

			if (fileLength < 1024.0)
			{
				return String.Format("{0} Byte", fileLength);
			}
			if (fileLength < 1048576.0)
			{
				return String.Format("{0:N3} KByte", fileLength / 1024.0);
			}
			if (fileLength < 1073741824.0)
			{
				return String.Format("{0:N3} MByte", (fileLength / 1024.0) / 1024.0);
			}
			return String.Format("{0:N3} GByte", ((fileLength / 1024.0) / 1024.0) / 1024.0);
		}

		public static String GetFormatFileLength(Single fileLength)
		{
			return GetFormatFileLength(Convert.ToDouble(fileLength));
		}

		public static String GetFormatFileLength(String fileLength)
		{
			return GetFormatFileLength(Double.Parse(fileLength));
		}

		/// <summary>
		/// 웹에플리케이션 물리적루트경로
		/// </summary>
		public static String WebApplicationPhysicalPath
		{
			get
			{
				return HostingEnvironment.ApplicationPhysicalPath;
			}
		}

		/// <summary>
		/// 웹에플리케이션 가상루트경로
		/// </summary>
		public static String WebApplicationVirtualPath
		{
			get
			{
				String _rootPath = HostingEnvironment.ApplicationVirtualPath;
				if (_rootPath.Length > 1)
				{
					_rootPath = _rootPath + "/";
				}
				return _rootPath;
			}
		}

		/// <summary>
		/// 전역 자바스크립트 Url
		/// </summary>
		/// <returns>Url</returns>
		public static String GetGlobalJavaScriptUrl()
		{
			return (VUtility.WebApplicationVirtualPath + "vboard/common/globaljavascript.js");
		}

		/// <summary>
		/// 전역 스타일시트 Url
		/// </summary>
		/// <returns>Url</returns>
		public static String GetGlobalStyleSheetUrl()
		{
			return (VUtility.WebApplicationVirtualPath + "vboard/common/globalstylesheet.css");
		}

		/// <summary>
		/// 멤버 사진 Url
		/// </summary>
		/// <param name="providerUserKey">멤버키</param>
		/// <returns>Url</returns>
		public static String GetMemberImageUrl(String providerUserKey)
		{
			if (providerUserKey == null)
				throw new ArgumentNullException("providerUserKey");

			if (String.IsNullOrEmpty(providerUserKey))
				throw new ArgumentOutOfRangeException("providerUserKey");

			return String.Format(VUtility.WebApplicationVirtualPath + "vboard/membership/handler/memberimage.ashx?key={0}", providerUserKey);
		}

		/// <summary>
		/// 새로고침 Url
		/// </summary>
		/// <returns>Url</returns>
		public static String GetRefreshPageUrl()
		{
			return (VUtility.WebApplicationVirtualPath + "vboard/common/refresh.aspx");
		}

		/// <summary>
		/// VWebGlobalValues.resx로부터 키에 해당하는 값을 문자열로 가져옵니다.
		/// </summary>
		/// <param name="key">리소스키</param>
		/// <returns>리소스문자열</returns>
		public static String GetVWebGlobalResource(String key)
		{
			if (key == null)
				throw new ArgumentNullException("key");

			if (String.IsNullOrEmpty(key))
				throw new ArgumentOutOfRangeException("key");

			return (String)HttpContext.GetGlobalResourceObject("VGlobalResources", key, System.Globalization.CultureInfo.CurrentCulture);
		}

		/// <summary>
		/// 전달된 예외개체와 포함하고 있는 InnerException의 예외메세지를 종합합니다.
		/// </summary>
		/// <param name="ex">예외개체</param>
		/// <returns>예외메세지</returns>
		public static String GetAmassExceptionMessage(System.Exception ex)
		{
			if (ex == null)
				throw new ArgumentNullException("ex");

			String message = ex.Message + "\r\n";

			if (ex.InnerException != null)
				message += GetAmassExceptionMessage(ex.InnerException);

			return message;
		}

		/// <summary>
		/// 메세지 페이지로 이동합니다.
		/// </summary>
		/// <param name="page">System.Web.UI.Page</param>
		/// <param name="message">메세지 내용</param>
		/// <param name="redirectUrl">메세지 표시후 이동할 주소</param>
		/// <param name="autoRedirectToReturnUrl">자동으로 이동할지 여부</param>
		/// <param name="redirectTimeout">자동으로 이동할때 기다리는 시간.(초)</param>
		public static void GoToMessagePage(System.Web.UI.Page page, String message, String redirectUrl, Boolean autoRedirectToReturnUrl, Int32 redirectTimeout)
		{
			MessagePageParameter messagePageParamter = new MessagePageParameter();
			messagePageParamter.Message = message;
			messagePageParamter.RedirectUrl = redirectUrl;
			messagePageParamter.AutoRedirectToReturnUrl = autoRedirectToReturnUrl;
			messagePageParamter.RedirectTimeout = redirectTimeout;

			page.Session["!VWeb_MessagePageParameter"] = messagePageParamter;

			page.Response.Clear();
			page.Server.Transfer(page.ResolveUrl("~/vboard/common/message.aspx"), true);
		}

		/// <summary>
		/// Alert창을 띄웁니다.
		/// </summary>
		/// <param name="page">현재 Page</param>
		/// <param name="content">내용</param>
		public static void ShowAlert(System.Web.UI.Page page, String content)
		{
			String key = "!VWeb_ScriptKey";

			if (!page.ClientScript.IsStartupScriptRegistered(key))
			{
				content = content.Replace("'", @"\'").Replace("\r\n", @"\n");
				page.ClientScript.RegisterStartupScript(page.ClientScript.GetType(), key, "alert('" + content + "');", true);
			}
		}

		/// <summary>
		/// MessagePanel을 띄웁니다.
		/// </summary>
		/// <param name="page">현재 Page</param>
		/// <param name="content">내용</param>
		/// <param name="enableCloseButton">닫기 버튼 출력</param>
		public static void ShowMessagePanel(System.Web.UI.Page page, String content, Boolean enableCloseButton)
		{
			String key = "!VWeb_ScriptKey";

			if (!page.ClientScript.IsStartupScriptRegistered(key))
				page.ClientScript.RegisterStartupScript(page.ClientScript.GetType(), key, "VWebGlobal_ShowMessagePanel('" + content + "', " + enableCloseButton.ToString().ToLower() + ");", true);
		}

		/// <summary>
		/// Alert창 자바스크립트. 스크립트 태그는 생략.
		/// </summary>
		/// <param name="content">내용</param>
		/// <returns>자바스크립트</returns>
		public static String GetAlertScript(String content)
		{
			return "alert('" + content.Replace("'", @"\'").Replace("\r\n", @"\n") +"');";
		}

		/// <summary>
		/// MessagePanel 자바스크립트. 스크립트 태그는 생략.
		/// </summary>
		/// <param name="content">내용</param>
		/// <param name="enableCloseButton">닫기 버튼 출력</param>
		/// <returns>자바스크립트</returns>
		public static String GetMessageScript(String content, Boolean enableCloseButton)
		{
			return "VWebGlobal_ShowMessagePanel('" + content + "', " + enableCloseButton.ToString().ToLower() + ");";
		}

		/// <summary>
		/// 문자열이 Guid형식인지 검사합니다.
		/// </summary>
		/// <param name="guid">검사할 문자열</param>
		/// <returns>검사결과</returns>
		public static Boolean IsGuid(String guid)
		{
			if (guid == null)
				throw new ArgumentNullException("guid");

			if (String.IsNullOrEmpty(guid))
				throw new ArgumentOutOfRangeException("guid");

			return System.Text.RegularExpressions.Regex.IsMatch(guid, @"^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$");
		}






		/// <summary>
		/// PublicationReport를 위해 사용됩니다. 게시판에 글, 댓글이 추가되거나 변경되는 경우 관리자 Email로 그 내용이 보내집니다.
		/// </summary>
		/// <param name="command">BoardThread.Add, BoardThread.Modify, BoardComment.Add, BoardComment.Modify등 어떠한 명령인지 관리자가 확인할 수 있는 명령 이름.</param>
		/// <param name="ip">아이피</param>
		/// <param name="username">사용자 이름</param>
		/// <param name="title">제목</param>
		/// <param name="content">내용</param>
		internal static Boolean SendSmtpMessage(String command, String ip, String username, String title, String content)
		{
			if (VWebConfigurationReader.Administrator.PublicationReport && !String.IsNullOrEmpty(VWebConfigurationReader.Administrator.Email))
			{
				SmtpClient a = new SmtpClient();

				String bodyFormat = "Command : {0}\r\n---\r\nIP : {1}\r\n---\r\nUserName : {2}\r\n---\r\nTitle : {3}\r\n---\r\nContent : {4}\r\n---\r\nDate : {5}";

				a.Send(VWebConfigurationReader.Administrator.Email,
					VWebConfigurationReader.Administrator.Email,
					command + " : " + username + " : " + DateTime.Now.ToString(),
					String.Format(bodyFormat, command, ip, username, title, content, DateTime.Now.ToString())
				);

				return true;
			}

			return false;
		}

		/// <summary>
		/// 컨트롤의 속성값을 가져옵니다. 현재값이 없으면 web.config의 값을 가져옵니다. 만약 web.config의 값이 없으면 기본값을 반환합니다.
		/// </summary>
		/// <param name="currentValue">현재값</param>
		/// <param name="property">web.config의 속성 이름</param>
		/// <param name="defaultValue">기본값</param>
		/// <returns></returns>
		internal static String GetControlSetting(String currentValue, String property, String defaultValue)
		{
			if (!String.IsNullOrEmpty(currentValue))
				return currentValue;

			VWebControlSetting setting = VWebConfigurationReader.ControlSettings[property];

			return setting != null ? setting.Value : defaultValue;
		}

		internal static Int32 GetControlSetting(Int32 min, Int32 max, Int32 currentValue, String property, Int32 defaultValue)
		{
			if (currentValue >= min && currentValue <= max)
				return currentValue;

			VWebControlSetting setting = VWebConfigurationReader.ControlSettings[property];

			if (setting == null)
				return defaultValue;
			else
			{
				Int32 settingValue = Int32.Parse(setting.Value);

				if (settingValue >= min && settingValue <= max)
					return settingValue;
				else
					return defaultValue;
			}
		}
	}
}
